let REQUEST_ENV = "online"; // 正式环境
REQUEST_ENV = 'release' // 预览环境
const ENV_CONFIG = {
  online: {
    request: "online",
    domainName: "",
  },
  release: {
    request: "release",
    domainName: "",
  },
};

export const ENV = ENV_CONFIG[REQUEST_ENV];

/**
 * 设置缓存
 * @@param {string} key
 * @@param {string} value
 */
export const setLocalStorage = (key, value) => {
  let params = JSON.stringify(value);
  uni.setStorageSync(ENV.request + "_" + key, params);
};
/**
 * 读取缓存
 * @@param {string} key
 */
export const getLocalStorage = (key) => {
  let result = uni.getStorageSync(ENV.request + "_" + key);
  if (result) {
    result = JSON.parse(result);
  } else {
    return null;
  }
  return result;
};
/**
 * 清除缓存
 * @@param {string} key
 */
export const getRemoveStorage = (key) => {
  uni.removeStorageSync(ENV.request + "_" + key);
};

// 登录授权
export const onLogin = () => {
  uni.reLaunch({ url: "/pagesBasis/login/index" });
};
/**
 * @param {*} str 字符串
 * @param {*} frontLen  前面保留位数
 * @param {*} endLen  后面保留位数
 * @returns 返回结果
 */
export function plusXing(str, frontLen, endLen) {
  var len = str.length - frontLen - endLen;
  var xing = "";
  for (var i = 0; i < len; i++) {
    xing += "*";
  }
  return str.substr(0, frontLen) + xing + str.substr(str.length - endLen);
}
/**
 * @param {*} v1 当前版本
 * @param {*} v2 最低版本
 * @returns
 */
export const compareVersion = (v1, v2) => {
  v1 = v1.split(".");
  v2 = v2.split(".");
  const len = Math.max(v1.length, v2.length);

  while (v1.length < len) {
    v1.push("0");
  }
  while (v2.length < len) {
    v2.push("0");
  }

  for (let i = 0; i < len; i++) {
    const num1 = parseInt(v1[i]);
    const num2 = parseInt(v2[i]);

    if (num1 > num2) {
      return 1;
    } else if (num1 < num2) {
      return -1;
    }
  }

  return 0;
};
/**
 * 保存图片到相册
 * @param {*} file 路径
 */
export const WeChatSavesImage = (file) => {
  uni.getSetting({
    success: (res) => {
      if (res.authSetting["scope.writePhotosAlbum"] === undefined) {
        uni.authorize({
          scope: "scope.writePhotosAlbum",
          success: () => {
            uni.saveImageToPhotosAlbum({
              filePath: file,
              success: () => {
                uni.showToast({
                  title: "图片已保存至相册",
                  icon: "none",
                  mask: true,
                });
              },
            });
          },
          fail: () => {
            uni.showToast({
              title: "图片保存失败",
              icon: "none",
              mask: true,
            });
          },
        });
        return;
      }
      if (res.authSetting["scope.writePhotosAlbum"]) {
        uni.saveImageToPhotosAlbum({
          filePath: file,
          success: () => {
            uni.showToast({
              title: "图片已保存至相册",
              icon: "none",
              mask: true,
            });
          },
        });
      } else {
        uni.showModal({
          content: "检测到您没打开【添加到相册】功能权限",
          confirmText: "去设置",
          cancelText: "取消",
          success: (res) => {
            if (res.confirm) {
              uni.openSetting({
                complete: () => {},
              });
            }
          },
        });
      }
    },
    fail: () => {},
  });
};
/**
 * 微信支付
 */
export const payAxios = (data) => {
  return new Promise((resolve, reject) => {
    uni.requestPayment({
      /** 时间戳，从 1970 年 1 月 1 日 00:00:00 至今的秒数，即当前的时间 */
      timeStamp: data.timeStamp,
      /** 随机字符串，长度为32个字符以下 */
      nonceStr: data.nonceStr,
      /** 统一下单接口返回的 prepay_id 参数值，提交格式如：prepay_id=*** */
      package: data.package,
      /** 签名算法 "MD5" | "HMAC-SHA256" */
      signType: data.signType,
      /** 签名，具体签名方案参见 [小程序支付接口文档](https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=3) */
      paySign: data.paySign,
      /** 接口调用结束的回调函数（调用成功、失败都会执行） */
      // complete: (res) => { },
      /** 接口调用成功的回调函数 */
      success: (res) => {
        resolve(res);
      },
      /** 接口调用失败的回调函数 */
      fail: (err) => {
        //   console.log("fail", err);
        reject(err);
      },
    });
  });
};
/**
 * @description 判断是否是手机号
 * @param str
 * @returns {boolean}
 */
export const isPhone = (str) => {
  const reg =
    /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
  return reg.test(str);
};
/**
 *
 * @param {number} n 随机长度
 * @returns
 */
export const randomString = (n) => {
  let str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  let tmp = "",
    i = 0,
    l = str.length;
  for (i = 0; i < n; i++) {
    tmp += str.charAt(Math.floor(Math.random() * l));
  }
  return tmp;
};
/**
 * 将科学计数法的数字转为字符串
 * 说明：运算精度丢失方法中处理数字的时候，如果出现科学计数法，就会导致结果出错
 * 4.496794759834739e-9  ==> 0.000000004496794759834739
 * 4.496794759834739e+9  ==> 4496794759.834739
 * @param  num
 */
export const toNonExponential = (num) => {
  if (num == null) {
    return num;
  }
  if (typeof num == "number") {
    const m = num.toExponential().match(/\d(?:\.(\d*))?e([+-]\d+)/);
    return num.toFixed(Math.max(0, (m[1] || "").length - m[2]));
  } else {
    return num;
  }
};
/**
 * 乘法 - js运算精度丢失问题
 * @param arg1  数1
 * @param arg2  数2
 * 0.0023 * 100 ==> 0.22999999999999998
 * {{ 0.0023 | multiply(100) }} ==> 0.23
 */
export const floatMultiply = (arg1, arg2) => {
  arg1 = Number(arg1);
  arg2 = Number(arg2);
  if ((!arg1 && arg1 !== 0) || (!arg2 && arg2 !== 0)) {
    return null;
  }
  arg1 = toNonExponential(arg1);
  arg2 = toNonExponential(arg2);
  let n1, n2;
  let r1, r2; // 小数位数
  try {
    r1 = arg1.toString().split(".")[1].length;
  } catch (e) {
    r1 = 0;
  }
  try {
    r2 = arg2.toString().split(".")[1].length;
  } catch (e) {
    r2 = 0;
  }
  n1 = Number(arg1.toString().replace(".", ""));
  n2 = Number(arg2.toString().replace(".", ""));
  return (n1 * n2) / Math.pow(10, r1 + r2);
};
/**
 * 除法 - js运算精度丢失问题
 * @param arg1  数1
 * @param arg2  数2
 * 0.0023 / 0.00001 ==> 229.99999999999997
 * {{ 0.0023 | divide(0.00001) }} ==> 230
 */
export const floatDivide = (arg1, arg2) => {
  arg1 = Number(arg1);
  arg2 = Number(arg2);
  if (!arg2) {
    return null;
  }
  if (!arg1 && arg1 !== 0) {
    return null;
  } else if (arg1 === 0) {
    return 0;
  }
  arg1 = toNonExponential(arg1);
  arg2 = toNonExponential(arg2);
  let n1, n2;
  let r1, r2; // 小数位数
  try {
    r1 = arg1.toString().split(".")[1].length;
  } catch (e) {
    r1 = 0;
  }
  try {
    r2 = arg2.toString().split(".")[1].length;
  } catch (e) {
    r2 = 0;
  }
  n1 = Number(arg1.toString().replace(".", ""));
  n2 = Number(arg2.toString().replace(".", ""));
  return floatMultiply(n1 / n2, Math.pow(10, r2 - r1));
  // return (n1 / n2) * Math.pow(10, r2 - r1);   // 直接乘法还是会出现精度问题
};
/**
 * 加法 - js运算精度丢失问题
 * @param arg1  数1
 * @param arg2  数2
 * 0.0023 + 0.00000000000001 ==> 0.0023000000000099998
 * {{ 0.0023 | plus(0.00000000000001) }} ==> 0.00230000000001
 */
export const floatAdd = (arg1, arg2) => {
  arg1 = Number(arg1) || 0;
  arg2 = Number(arg2) || 0;
  arg1 = toNonExponential(arg1);
  arg2 = toNonExponential(arg2);
  let r1, r2, m;
  try {
    r1 = arg1.toString().split(".")[1].length;
  } catch (e) {
    r1 = 0;
  }
  try {
    r2 = arg2.toString().split(".")[1].length;
  } catch (e) {
    r2 = 0;
  }
  m = Math.pow(10, Math.max(r1, r2));
  return (floatMultiply(arg1, m) + floatMultiply(arg2, m)) / m;
};
/**
 * 减法 - js运算精度丢失问题
 * @param arg1  数1
 * @param arg2  数2
 * 0.0023 - 0.00000011  ==>  0.0022998899999999997
 * {{ 0.0023 | minus( 0.00000011 ) }}  ==>  0.00229989
 */
export const floatSub = (arg1, arg2) => {
  arg1 = Number(arg1) || 0;
  arg2 = Number(arg2) || 0;
  arg1 = toNonExponential(arg1);
  arg2 = toNonExponential(arg2);
  let r1, r2, m, n;
  try {
    r1 = arg1.toString().split(".")[1].length;
  } catch (e) {
    r1 = 0;
  }
  try {
    r2 = arg2.toString().split(".")[1].length;
  } catch (e) {
    r2 = 0;
  }
  m = Math.pow(10, Math.max(r1, r2));
  // 动态控制精度长度
  n = r1 >= r2 ? r1 : r2;
  return ((floatMultiply(arg1, m) - floatMultiply(arg2, m)) / m).toFixed(n);
};
/**
 * 取余 - js运算精度丢失问题
 * @param arg1  数1
 * @param arg2  数2
 * 12.24 % 12  ==> 0.2400000000000002
 * {{ 12.24 | mod( -12 ) }}  ==>  0.24
 */
export const floatMod = (arg1, arg2) => {
  arg1 = Number(arg1);
  arg2 = Number(arg2);
  if (!arg2) {
    return null;
  }
  if (!arg1 && arg1 !== 0) {
    return null;
  } else if (arg1 === 0) {
    return 0;
  }
  let intNum = arg1 / arg2;
  intNum = intNum < 0 ? Math.ceil(arg1 / arg2) : Math.floor(arg1 / arg2); // -1.02 取整为 -1; 1.02取整为1
  let intVal = floatMultiply(intNum, arg2);
  return floatSub(arg1, intVal);
};
/**
 * 小数或整数(不可以负数)
 * @param val 当前值字符串
 * @returns 返回处理后的字符串
 */
export const verifyNumberIntegerAndFloat = (val) => {
  // 匹配空格
  let v = val.replace(/(^\s*)|(\s*$)/g, "");
  // 只能是数字和小数点，不能是其他输入
  v = v.replace(/[^\d.]/g, "");
  // 以0开始只能输入一个
  v = v.replace(/^0{2}$/g, "0");
  // 保证第一位只能是数字，不能是点
  v = v.replace(/^\./g, "");
  // 小数只能出现1位
  v = v.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
  // 小数点后面保留2位
  v = v.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3");
  // 返回结果
  return v;
};
/**
 * 手机号码
 * @param val 当前值字符串
 * @returns 返回 true: 手机号码正确
 */
export const verifyPhone = (val) => {
  // false: 手机号码不正确
  if (
    !/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(
      val
    )
  )
    return false;
  // true: 手机号码正确
  else return true;
};
/**
 * 函数节流
 * @param {*} fn
 * @param {*} gapTime
 * @returns
 */
export const throttle = (fn, gapTime) => {
  if (gapTime == null || gapTime == undefined) {
    gapTime = 1500;
  }
  let _lastTime = null;
  return () => {
    let _nowTime = +new Date();
    if (_nowTime - _lastTime > gapTime || !_lastTime) {
      fn.apply(this, arguments);
      _lastTime = _nowTime;
    }
  };
};
